/*
    user模块controller
 */
//数据库方法
const mysqlModel=require('../lib/users')
const baseModel=require('../lib/base')
//token登录凭证
const jwt=require('jsonwebtoken')
//数据库默认配置
const {config}=require('../config/default')
//错误处理
const ApiErrorNames=require('../error/ApiErrorNames')
//日期库
const moment = require('moment')
//获取登录ip
const getIp = require('../util/getIp')
//生成随机id
const { nanoid } = require('nanoid');
//md5加密密码
const md5 = require('md5');
//阿里云oss方法
const ali=require('../util/aliOSS_utils')

/*
 * 普通登录
 */
let login = async (ctx, next) => {
    const { body } = ctx.request
    try {
        const user = await mysqlModel.findUser(body['workNumber'])
        if (!user) {
            ctx.body = ApiErrorNames.getErrorInfo(ApiErrorNames.USER_NOT_EXIST)
            return
        }
        const {password} = (await user)
        const pwd = body.password
        // 匹配加密后的密码是否相等
        if (password === pwd) {
            const isHr=user['workNumber']<'10000'
            let data = {
                name:user['name'],
                token_time:moment().format('YYYY-MM-DD HH:mm:ss'),
                msg: '登录成功',
                isHr:isHr,
                // 生成 token 返回给客户端
                token: getToken({
                    workNumber:user['workNumber'],
                    name:user['name'],
                    isHr:isHr
                })
            }
            ctx.body = ApiErrorNames.getSuccessInfo(data)
        } else {
            ctx.body = ApiErrorNames.getErrorInfo(ApiErrorNames.USER_LOGIN_ERROR)
        }
    } catch (error) {
        ApiErrorNames.errorCatch(error, ctx)
    }
}

/*
 * 获取用户信息
 */
let getUserList = async (ctx) => {
    try{
        const token=ctx.headers.authorization
        let payload
        if(token){
            //鉴权
            payload=await jwt.verify(token.split(' ')[1],config.secret)
            let data= await mysqlModel.getUserList()
            let result=[]
            data.forEach(function(user){
                delete user.password
                if(user.workNumber>'10000'){
                    result.push(user)
                }
            })
            ctx.body=ApiErrorNames.getSuccessInfo(result)
        }
    }catch (e) {
        ApiErrorNames.errorCatch(e,ctx)
    }
}

/*
 * 通过ID获取用户信息
 */
let userInfoById = async (ctx) => {
    try {
        const token = ctx.headers.authorization
        let payload
        if (token) {
            await jwt.verify(token.split(' ')[1], config.secret) // 解密，获取payload
            const user = await mysqlModel.findUserInfoById(ctx.params.id)
            if (!user) {
                //找不到用户返回空对象
                ctx.body = ApiErrorNames.getSuccessInfo({})
            } else {
                ctx.body = ApiErrorNames.getSuccessInfo(user)
            }
        } else {
            ctx.body = ApiErrorNames.getErrorInfo(ApiErrorNames.INVALID_TOKEN)
        }
    } catch (error) {
        ApiErrorNames.errorCatch(error, ctx)
    }
}

/*
 * 添加待入职员工
 */
let register = async (ctx) => {
    const { body } = ctx.request
    const token = ctx.headers.authorization
    try {
        let payload = await jwt.verify(token.split(' ')[1], config.secret) // 解密，获取payload
        const user = await mysqlModel.findUser(body.workNumber)
        if (user) {
            ctx.body = ApiErrorNames.getErrorInfo(ApiErrorNames.USER_HAS_EXISTED)
            return
        }
        const contractId = nanoid(6)
        let info = [
            {
                workNumber:body.workNumber,
                name:body.name,
                email: body.email,
                post: body.post,
                status: 0,
                department:body.department
            },
            {
                contractId:contractId,
                contractName:`${body.name}的入职合同`,
                isDel:0,
                receiveUser:body.name,
                launchTime:moment().format('YYYY-MM-DD HH:mm:ss'),
                ddl:moment().add(7,'days').format('YYYY-MM-DD HH:mm:ss'),
                status:0,
                userEmail:body.email,
                launchUser:payload.name,
            },
            {
                contractId:contractId,
                contractTitle:`${body.name}的入职合同`,
                contractContent:`亲爱的${body.name}:<br/>您的岗位是${body.department}-${body.post}<br/>阿森纳北京市麦凯龙那附近阿里纳斯客服呢纳斯达克兰兰删除杰克逊你欺骗我能碰到佛阿萨哦啊技术的擦了形成马拉喀什就怕`,
                contractDate:moment().format('YYYY-MM-DD'),
                partyA:'我的公司',
                partyB:body.name
            }
        ]
        await mysqlModel
            .register(info)
            .then(() => {
                ctx.body = ApiErrorNames.getSuccessInfo(`新员工 ${body.name} 已为待入职状态,入职合同已发放!`)
            })
            .catch(() => {
                ctx.body = ApiErrorNames.getErrorInfo(ApiErrorNames.UNKNOWN_ERROR)
            })
    } catch (error) {
        ApiErrorNames.errorCatch(error, ctx)
    }
}

/*
  管理员删除用户
 */
let deleteUser=async (ctx,next)=>{
    try{
        const token=ctx.headers.authorization
        let payload
        let deleteId=ctx.params.id
        if(token){
            //鉴权 管理员可以删除所有人 普通用户只能删除/注销自己账户
            payload=await jwt.verify(token.split(' ')[1],config.secret)
            if (payload.user===deleteId||payload.roleId==='1001'){
                await mysqlModel.deleteUserById(deleteId)
                    .catch((err => {
                        ctx.body = ApiErrorNames.getErrorInfo(ApiErrorNames.DATA_IS_WRONG)
                    }))
                ctx.body=ApiErrorNames.getSuccessInfo("删除成功!")
            }
            else{
                ApiErrorNames.getErrorInfo(ApiErrorNames.PERMISSION_NO_ACCESS)
            }
        }
    }catch (e) {
        ApiErrorNames.errorCatch(e,ctx)
    }
}
/*
 管理员给普通用户分配角色
 */
let allocateRole=async (ctx,next)=>{
    const { body } = ctx.request
    const {id,newRoleId}=body
    try{
        const token=ctx.headers.authorization
        let payload
        if(token){
            //鉴权 只有管理员可以分配角色
            payload=await jwt.verify(token.split(' ')[1],config.secret)
            if (payload.roleId==='1001'){
                await mysqlModel.allocateRole(id,newRoleId)
                    .catch((err => {
                        ctx.body = ApiErrorNames.getErrorInfo(ApiErrorNames.DATA_IS_WRONG)
                    }))
                ctx.body=ApiErrorNames.getSuccessInfo("分配成功!")
            }
            else{
                ApiErrorNames.getErrorInfo(ApiErrorNames.USER_ACCOUNT_FORBIDDEN)
            }
        }
    }catch (e) {
        ApiErrorNames.errorCatch(e,ctx)
    }
}

/*
 * 退出登录
 */
let logout = async (ctx, next) => {
    try {
        ctx.body = ApiErrorNames.getSuccessInfo()
    } catch (error) {
        ApiErrorNames.errorCatch(error, ctx)
    }
}
/*
    token签发
 */
function getToken(payload={}){
    return jwt.sign(payload,config.secret,{expiresIn: '12h'})
}
/*
    获取当前操作用户的角色
 */
function getUserRole(id){
    return baseModel.getRoleByUserId(id)
}
module.exports={
    login,
    register,
    logout,
    deleteUser,
    userInfoById,
    getUserList,
    allocateRole
}
